package com.sebscape.sebcms.security.services;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;

import com.sebscape.sebcms.pages.domain.Page;
import com.sebscape.sebcms.pages.persistence.PageDao;

public class CmsPageLoaderInterceptor extends AbstractInterceptor implements StrutsStatics {

	private static final long serialVersionUID = -6669254945284973914L;
	private static Log log = LogFactory.getLog( CmsPageLoaderInterceptor.class );
	
	public static final String SUCCESS = "success";
	public static final String DENIED = "denied";
	private String uri; // the uri which will be uses by action-result for success.
	
	public String getUri(){
		return this.uri;
	}
	
	public String intercept (ActionInvocation invocation) throws Exception {
		log.debug( "CmsPageLoaderInterceptor invoked...");
	    // Get the action context from the invocation so we can access the
	    // HttpServletRequest and HttpSession objects.
	    final ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
		try {
			// do the processing.
			processBefore( request );
			return invocation.invoke ();
		} catch (Exception e) {
			// THis means the user is NOT logged in.
			log.debug("Exception raised in SimpleFilter: " + e.getMessage() );
			return DENIED;
		}// end catch
	} // end method

	private void processBefore(HttpServletRequest request)
	throws Exception{
		// are they trying to view a CMS page?
		log.debug("CmsPageLoaderInterceptor: looking at uri =  " + request.getRequestURI()  );
		if( request.getRequestURI().startsWith("/page/view") ){
			//get the page.
			log.debug("CmsPageLoaderInterceptor: This is a CMS-Page URI - so fetch it.");
			Page page = null;
			try {
				PageDao dao = new PageDao();
				if( request.getParameter( "name" ) != null ){
					page = dao.findByName( request.getParameter( "name" ) );
				} else if( request.getParameter( "id" ) != null ){
					page = dao.load( Long.valueOf( request.getParameter( "id" ) ) );
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if( page != null ){
				log.debug("CmsPageLoaderInterceptor: remembering page \"" + page.getName() + "\" as request.sebCMS_page.");
				request.setAttribute("sebCMS_page", page);
			}
		} else {
			log.debug("CmsPageLoaderInterceptor: This is a NOT a CMS-Page URI.");
		}
	}
}